package db

import (
	"fmt"
	"github.com/google/uuid"
	"gomonitor-server/src/domain"
	"gomonitor-server/src/mylog"
)

func QueryTagByName(tagName string, dbTool *DbTool) (domain.HostTag, error) {
	var hostTag domain.HostTag
	result := dbTool.db.Model(&domain.HostTag{}).Where("tag = ?", tagName).First(&hostTag)
	if result.Error != nil {
		return hostTag, result.Error
	}
	if result.RowsAffected > 0 {
		// 成功赋值给 hostState
		return hostTag, nil
	} else {
		// hostState 不存在
		return hostTag, fmt.Errorf("tag %s not found", tagName)
	}
}
func AddHostTag(ip string, hostname string, tagName string, dbTool *DbTool) error {
	hostStateId, err := GetHostStateByIpAndHostname(ip, hostname, dbTool)
	if err != nil {
		return err
	}
	var tagId string
	hostTag, err := QueryTagByName(tagName, dbTool)
	if err != nil {
		tagId = uuid.New().String()
		hostTag := &domain.HostTag{
			ID:  tagId,
			Tag: tagName,
		}
		dbTool.db.Model(&domain.HostTag{}).Create(hostTag)
	} else {
		tagId = hostTag.ID
	}
	var hostHostTags []domain.HostHostTag
	dbTool.db.Model(&domain.HostHostTag{}).Where("tag_id=? and host_state_id=?", tagId, hostStateId).Find(&hostHostTags)
	if len(hostHostTags) == 0 {
		hostHostTag := &domain.HostHostTag{
			ID:          uuid.New().String(),
			TagId:       tagId,
			HostStateId: hostStateId,
		}
		dbTool.db.Model(&domain.HostHostTag{}).Create(hostHostTag)
	}
	return nil
}

func AddIpListTag(ipList []string, tag string) error {
	dbTool, err := GetConnection()
	if err != nil {
		return err
	} else {
		hostStates, err := FindHostStateByIp(&ipList, dbTool)
		if err != nil {
			return err
		} else {
			for _, state := range hostStates {
				err := AddHostTag(state.IP, state.Hostname, tag, dbTool)
				if err != nil {
					return err
				}
			}
		}
		return nil
	}
}
func DeleteIpListTag(ipList []string, tag string) error {
	dbTool, err := GetConnection()
	if err != nil {
		return err
	} else {
		hostStates, err := FindHostStateByIp(&ipList, dbTool)
		if err != nil {
			return err
		} else {
			hostTag, err := QueryTagByName(tag, dbTool)
			if err != nil {
				return err
			} else {
				for _, state := range hostStates {
					mylog.Logger.Debugf("delete HostHostTag, host_state_id: %s, tag_id: %s", state.ID, hostTag.ID)
					dbTool.db.Model(&domain.HostHostTag{}).Where("host_state_id=? and tag_id=?", state.ID, hostTag.ID).Delete(&domain.HostHostTag{})
				}
			}

		}
		return nil
	}
}
